package cn.com.kh;

import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class apiFileDownZIP extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final Log log = LogFactory.getLog(apiFileDownZIP.class);
    public static EliteBean eliteBean;

    private static final String classString = "apiFileProxy";

    public void destroy() {
        super.destroy();
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        String fileurl = KHUtil.FastJsonNull(request.getParameter("fileurl"));
        String type = KHUtil.FastJsonNull(request.getParameter("type"));
        log.debug("原始Get请求参数fileurl:" + fileurl + " type:" + type);

        String fileName = fileurl.trim();
        fileName = fileName.substring(fileName.lastIndexOf("/") + 1);

        if (KHUtil.isNull(fileName)) {
            fileName = KHUtil.getRandomString(6);
        }

        if (KHUtil.isNull(fileurl)) {
            log.warn("FileURL 为空时不处理：" + fileurl);
            return;
        }

        try {
            String groovy_Path = KHDBConfig.getParamConfig(eliteBean, "Groovy_TempFilePath");

            if (!fileurl.startsWith("http")) {
                fileurl = KHDBConfig.getAPIURL(eliteBean, "NGS-FS-get_url") + "?file=" + URLEncoder.encode(fileurl, "UTF-8");
            }
            log.debug("文件下载URL:" + fileurl);

            // 下载文件
            String saveFile = groovy_Path + fileName;
            log.debug("下载文件路径:" + saveFile);
            boolean downloadRes = Util.httpDownLoadFile(fileurl, saveFile, 60000);
            log.debug("下载文件结果:" + downloadRes);

            // 压缩文件
            String saveZIPFile = fileName + ".zip";
            log.debug("压缩文件路径:" + saveZIPFile);
            List<String> fileList = new ArrayList<String>();
            fileList.add(saveFile);
            String saveZIPPath = Util.zip(fileList, saveZIPFile);
            log.debug("压缩文件结果:" + saveZIPPath);

            // 上传文件
            String redirectURL = uploadNGS(eliteBean, saveZIPPath);
            log.debug("上传文件结果:" + redirectURL);

            response.sendRedirect(redirectURL);

        } catch (Exception e) {
            log.error("接口处理异常", e);

        }
    }

    public void init() throws ServletException {

        log.info("接口FileDownZIP服务" + classString + " 开始初始化...");
        eliteBean = getEliteBean();

        log.info("接口FileDownZIP服务" + classString + " 初始化完成...");
    }

    private EliteBean getEliteBean() {
        try {
            ServletContext application = getServletContext();
            WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(application);
            return (EliteBean) wac.getBean("ebean");
        } catch (Exception e) {
            log.error("接口FileDownZIP初始化获取EliteBean失败!", e);
        }
        return null;
    }

    public static String uploadNGS(EliteBean eliteBean, String srcFileName) {

        try {
            String ngsFSToken = Util.getAuthToken(KHDBConfig.getAPIURL(eliteBean, "NGS-FS-authUrl"), KHDBConfig.getParamConfig(eliteBean, "NGS_InnerID"), KHDBConfig.getParamConfig(eliteBean, "NGS_InnerPWD"));
            log.debug("获取NGS上次Token：" + ngsFSToken);

            File tempFile = new File(srcFileName.trim());
            String fileName = tempFile.getName();

            String uploadResult = Util.uploadFile(KHDBConfig.getAPIURL(eliteBean, "NGS-FS-upload_url"), srcFileName, "/wo_atta_down", getNameWithoutSuffix(fileName), "", ngsFSToken);
            log.debug("文件上传NGS结果：" + uploadResult);

            JSONObject resultJson = JSONObject.fromObject(uploadResult);

            String code = resultJson.getString("code");
            if (code.equals("1")) {
                return KHDBConfig.getAPIURL(eliteBean, "NGS-OuterDomain") + "fs/get?file=" + URLEncoder.encode(resultJson.getString("value"), "UTF-8");
            } else {
                return null;
            }
        } catch (Exception e) {
            log.error("文件上传NGS结果异常!");
        }
        return null;
    }

    public static String getNameWithoutSuffix(String filename) {
        try {
            if ((filename != null) && (filename.length() > 0)) {
                int dot = filename.lastIndexOf(".");
                if ((dot > -1) && (dot < filename.length()))
                    return filename.substring(0, dot);
            }
        } catch (Exception e) {
            log.error(e);
        }
        return filename;
    }

}